package com.wjerp.tplus.server.common.utils;

import com.wjerp.tplus.server.api.request.AddReimburseMemberInfoRequest;
import com.wjerp.tplus.server.common.constant.DeleteFlag;
import com.wjerp.tplus.server.common.exception.ServiceException;
import com.wjerp.tplus.server.domain.entity.invoice.mng.ReimburseMemberInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * excel文件操作通用类
 * @author lishuailei
 */
@Component
public class ExcelComponent {

    private static final Logger logger = LoggerFactory.getLogger(ExcelComponent.class);

    private static final String EXCEL_XLSX = "XLSX";

    /**
     * 获取导入的报销人员信息
     * @param file
     * @return
     */
    public List<AddReimburseMemberInfoRequest> getReimburseInfoByFile(MultipartFile file) throws ServiceException {
        if (file.isEmpty()) {
            throw new ServiceException("上传失败，因为文件是空的");
        }

        List<AddReimburseMemberInfoRequest> reimburseMemberInfoList = new ArrayList<>();
        try {
            File diskFile = saveFile(file);
            //文件类型
            String excelType = file.getOriginalFilename()
                    .substring(file.getOriginalFilename().length() - 4);
            reimburseMemberInfoList = getReimburseInfoExcelData(diskFile,excelType);
        }catch (IOException ex){
            logger.error("操作文件异常",ex);
            throw new ServiceException("操作文件异常,异常信息：{}",ex.getMessage());
        }
        return reimburseMemberInfoList;
    }

    /**
     * 存储文件信息
     * @param file
     * @return
     * @throws IOException
     */
    private File saveFile(MultipartFile file) throws IOException {
        File targetFile=new File(file.getOriginalFilename());
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(targetFile));
        out.write(file.getBytes());
        out.flush();
        out.close();
        return targetFile;
    }



    /**
     * 获取报销人员EXCEL数据
     * @param diskFile 本地文件信息
     * @param excelType 文件类型
     * @return 整理后的数据
     */
    private List<AddReimburseMemberInfoRequest> getReimburseInfoExcelData(File diskFile, String excelType) throws IOException, ServiceException {
        List<AddReimburseMemberInfoRequest> reimburseMemberInfoList = new ArrayList<>();
        InputStream inputStream=new FileInputStream(diskFile);
        Workbook workBook = null;
        if (!excelType.equalsIgnoreCase(EXCEL_XLSX)) {
            workBook = new HSSFWorkbook(inputStream);
        } else {
            workBook = new XSSFWorkbook(inputStream);
        }

        Sheet sheet = workBook.getSheet("sheet1");
        if (sheet == null) {
            throw new ServiceException("excel中不存在名称为【sheet1】的标签页");
        }
        // 获取到Excel文件中的所有行数
        int rows = sheet.getPhysicalNumberOfRows();

        Map<Integer,String> customerMap=new HashMap<>(3);
        int titleCellCount = sheet.getRow(0).getLastCellNum();
        for(Integer i=0;i<titleCellCount;i++){
            // 获取到列的值
            final Cell cell =  sheet.getRow(0).getCell(i);
            if (cell != null) {
                customerMap.put(i,cell.getStringCellValue());
            }
        }

        // 遍历行,默认从第0行开始
        for (int i = 1; i <= rows; i++) {
            // 读取左上端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
                // 获取到Excel文件中的所有的列
                int cells = row.getLastCellNum();
                AddReimburseMemberInfoRequest reimburseMemberInfo=new AddReimburseMemberInfoRequest();
                // 遍历列
                for (int j = 0; j <= cells; j++) {
                    // 获取到列的值
                    final Cell cell = row.getCell(j);
                    if (cell != null) {
                        switch (customerMap.get(j)) {
                            case "编码":
                                reimburseMemberInfo.setReimburseCode(cell.getStringCellValue());
                                break;
                            case "名称":
                                reimburseMemberInfo.setName(cell.getStringCellValue());
                                break;
                        }
                    }
                }
                reimburseMemberInfoList.add(reimburseMemberInfo);
            }
        }
        return reimburseMemberInfoList;
    }
}
